<template>
  <div class="image-generation-container">
    <div class="generation-header">
      <a-button class="back-button" @click="goBack">
        <template #icon>
          <icon-left />
        </template>
        返回
      </a-button>
      <h1 class="page-title">图片生成</h1>
    </div>

    <div class="input-section" v-if="!isGenerating && !generatedImage">
      <div class="text-input-container">
        <div class="selected-styles" v-if="getPrompt">
          <a-tag 
            v-for="(style, index) in getPrompt.split('，')"
            :key="index"
            closable
            class="style-tag"
            @close="handleStyleTagClose(getStyleType(index))"
          >
            {{ style }}
          </a-tag>
        </div>
        <a-textarea
          v-model="textInput"
          :auto-size="{ minRows: 3, maxRows: 5 }"
          placeholder="描述你想要的吉卜力风格场景..."
        />
        <div class="input-tools">
          <div class="tool-icons">
            <a-dropdown trigger="click" position="bl">
              <a-button 
                shape="circle" 
                class="tool-btn"
                :class="{ 'tool-btn-active': selectedStyles.ghibli !== 'none' }"
              >
                <template #icon>
                  <icon-apps />
                </template>
              </a-button>
              <template #content>
                <a-doption
                  v-for="item in styleMenus.ghibli"
                  :key="item.value"
                  :value="item.value"
                  @click="selectedStyles.ghibli = item.value"
                >
                  {{ item.label }}
                </a-doption>
              </template>
            </a-dropdown>
            <a-dropdown trigger="click" position="bl">
              <a-button 
                shape="circle" 
                class="tool-btn"
                :class="{ 'tool-btn-active': selectedStyles.ratio !== 'none' }"
              >
                <template #icon>
                  <icon-image />
                </template>
              </a-button>
              <template #content>
                <a-doption
                  v-for="item in styleMenus.ratio"
                  :key="item.value"
                  :value="item.value"
                  @click="selectedStyles.ratio = item.value"
                >
                  {{ item.label }}
                </a-doption>
              </template>
            </a-dropdown>
            <a-dropdown trigger="click" position="bl">
              <a-button 
                shape="circle" 
                class="tool-btn"
                :class="{ 'tool-btn-active': selectedStyles.color !== 'none' }"
              >
                <template #icon>
                  <icon-moon />
                </template>
              </a-button>
              <template #content>
                <a-doption
                  v-for="item in styleMenus.color"
                  :key="item.value"
                  :value="item.value"
                  @click="selectedStyles.color = item.value"
                >
                  {{ item.label }}
                </a-doption>
              </template>
            </a-dropdown>
            <a-dropdown trigger="click" position="bl">
              <a-button 
                shape="circle" 
                class="tool-btn"
                :class="{ 'tool-btn-active': selectedStyles.angle !== 'none' }"
              >
                <template #icon>
                  <icon-camera />
                </template>
              </a-button>
              <template #content>
                <a-doption
                  v-for="item in styleMenus.angle"
                  :key="item.value"
                  :value="item.value"
                  @click="selectedStyles.angle = item.value"
                >
                  {{ item.label }}
                </a-doption>
              </template>
            </a-dropdown>
          </div>
          <a-button 
            type="primary" 
            class="generate-btn"
            @click="handleGenerate"
          >
            生成图片
            <template #icon>
              <icon-right />
            </template>
          </a-button>
          <!-- 添加测试按钮，仅在开发环境显示 -->
          <a-button 
            v-if="isDevelopment"
            type="outline" 
            status="warning"
            class="test-btn"
            @click="testCorsProxy"
          >
            测试CORS代理
          </a-button>
        </div>
      </div>
    </div>

    <!-- 生成中页面 -->
    <div class="generation-progress" v-if="isGenerating">
      <div class="progress-container">
        <div class="progress-animation">
          <icon-loading class="loading-icon" />
        </div>
        <h2 class="progress-title">正在生成您的图片</h2>
        <p class="progress-description">AI 正在根据您的描述创作吉卜力风格图片...</p>
        
        <!-- 假进度条 -->
        <div class="progress-bar-container">
          <div class="progress-bar" :style="{ width: `${progressPercentage}%` }"></div>
        </div>
        <div class="progress-percentage">{{ progressPercentage }}%</div>
        
        <div class="progress-steps">
          <div class="step" :class="{ 'active': progressPercentage >= 25 }">
            <div class="step-icon">1</div>
            <div class="step-text">分析提示词</div>
          </div>
          <div class="step" :class="{ 'active': progressPercentage >= 50 }">
            <div class="step-icon">2</div>
            <div class="step-text">构建场景</div>
          </div>
          <div class="step" :class="{ 'active': progressPercentage >= 75 }">
            <div class="step-icon">3</div>
            <div class="step-text">应用风格</div>
          </div>
          <div class="step" :class="{ 'active': progressPercentage >= 100 }">
            <div class="step-icon">4</div>
            <div class="step-text">完成创作</div>
          </div>
        </div>

        <div class="generation-tips">
          <p>生成过程通常需要 10-15 秒，请耐心等待...</p>
        </div>
      </div>
    </div>

    <!-- 生成结果页面 -->
    <div v-if="generatedImage && !isGenerating" class="result-container">
      <div class="image-card">
        <img :src="generatedImage" class="generated-image" alt="Generated Image" />
        <div class="image-info">
          <p class="revised-prompt">
            <span class="prompt-label">提示词：</span> {{ revisedPrompt || getPrompt }}
          </p>
          <div class="image-actions">
            <a-button type="primary" @click="downloadImage(generatedImage)">
              下载图片
            </a-button>
            <a-button @click="handleGenerate">
              重新生成
            </a-button>
            <a-button @click="resetGeneration">
              新建创作
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
import { generateImage } from '../services/api'
import {
  IconApps,
  IconImage,
  IconMoon,
  IconCamera,
  IconRight,
  IconLoading,
  IconLeft
} from '@arco-design/web-vue/es/icon'

const router = useRouter()

interface StyleOption {
  label: string
  value: string
}

interface StyleMenus {
  ghibli: StyleOption[]
  ratio: StyleOption[]
  color: StyleOption[]
  angle: StyleOption[]
}

// 文本输入
const textInput = ref('')

// 选中的风格
const selectedStyles = ref({
  ghibli: 'none',
  ratio: 'none',
  color: 'none',
  angle: 'none'
})

// 风格菜单
const styleMenus: StyleMenus = {
  ghibli: [
    { label: '宫崎骏风格', value: '宫崎骏风格' },
    { label: '千与千寻风格', value: '千与千寻风格' },
    { label: '龙猫风格', value: '龙猫风格' },
    { label: '天空之城风格', value: '天空之城风格' },
    { label: '哈尔的移动城堡风格', value: '哈尔的移动城堡风格' }
  ],
  ratio: [
    { label: '横版 16:9', value: '横版' },
    { label: '方形 1:1', value: '方形' },
    { label: '竖版 9:16', value: '竖版' }
  ],
  color: [
    { label: '明亮色调', value: '明亮色调' },
    { label: '暗色调', value: '暗色调' },
    { label: '暖色调', value: '暖色调' },
    { label: '冷色调', value: '冷色调' }
  ],
  angle: [
    { label: '特写镜头', value: '特写镜头' },
    { label: '远景镜头', value: '远景镜头' },
    { label: '俯视角度', value: '俯视角度' },
    { label: '仰视角度', value: '仰视角度' }
  ]
}

// 判断是否为开发环境
const isDevelopment = ref(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1')

// 生成状态
const isGenerating = ref(false)
const generatedImage = ref('')
const revisedPrompt = ref('')

// 假进度条
const progressPercentage = ref(0)
let progressInterval: number | null = null

// 获取完整提示词
const getPrompt = computed(() => {
  const parts = []
  
  if (selectedStyles.value.ghibli !== 'none') {
    parts.push(selectedStyles.value.ghibli)
  }
  
  if (selectedStyles.value.ratio !== 'none') {
    parts.push(selectedStyles.value.ratio)
  }
  
  if (selectedStyles.value.color !== 'none') {
    parts.push(selectedStyles.value.color)
  }
  
  if (selectedStyles.value.angle !== 'none') {
    parts.push(selectedStyles.value.angle)
  }
  
  // 添加用户输入的文本
  if (textInput.value.trim()) {
    parts.push(textInput.value.trim())
  }
  
  return parts.length > 0 ? parts.join('，') : ''
})

// 获取风格类型
const getStyleType = (index: number) => {
  const styles = getPrompt.value.split('，')
  const style = styles[index]
  
  // 判断风格类型
  if (styleMenus.ghibli.some(item => item.value === style)) {
    return 'ghibli'
  } else if (styleMenus.ratio.some(item => item.value === style)) {
    return 'ratio'
  } else if (styleMenus.color.some(item => item.value === style)) {
    return 'color'
  } else if (styleMenus.angle.some(item => item.value === style)) {
    return 'angle'
  }
  
  return ''
}

// 处理风格标签关闭
const handleStyleTagClose = (type: string) => {
  if (type && type in selectedStyles.value) {
    selectedStyles.value[type as keyof typeof selectedStyles.value] = 'none'
  }
}

// 启动假进度条
const startFakeProgress = () => {
  // 重置进度
  progressPercentage.value = 0
  
  // 清除可能存在的旧定时器
  if (progressInterval) {
    clearInterval(progressInterval)
  }
  
  // 设置新的进度更新定时器
  progressInterval = window.setInterval(() => {
    // 进度增加逻辑
    if (progressPercentage.value < 95) {
      // 前期快速增加
      if (progressPercentage.value < 30) {
        progressPercentage.value += 3
      } 
      // 中期缓慢增加
      else if (progressPercentage.value < 70) {
        progressPercentage.value += 1
      } 
      // 后期更缓慢增加
      else {
        progressPercentage.value += 0.5
      }
    }
  }, 200)
}

// 完成进度条
const completeProgress = () => {
  // 清除定时器
  if (progressInterval) {
    clearInterval(progressInterval)
    progressInterval = null
  }
  
  // 直接设置为100%
  progressPercentage.value = 100
  
  // 短暂延迟后显示结果
  setTimeout(() => {
    isGenerating.value = false
  }, 500)
}

// 生成图片
const handleGenerate = async () => {
  if (!getPrompt.value) {
    Message.warning('请输入描述或选择风格')
    return
  }
  
  try {
    // 设置生成状态
    isGenerating.value = true
    generatedImage.value = ''
    revisedPrompt.value = ''
    
    // 启动假进度条
    startFakeProgress()
    
    // 调用API生成图片
    const result = await generateImage({
      model: 'dall-e-3',
      prompt: getPrompt.value,
      n: 1,
      size: '1024x1024'
    })
    
    // 设置生成结果
    if (result.success && result.result.data && result.result.data.length > 0) {
      generatedImage.value = result.result.data[0].url
      revisedPrompt.value = result.result.data[0].revised_prompt
      
      // 完成进度条
      completeProgress()
    } else {
      throw new Error('生成失败')
    }
  } catch (error) {
    console.error('生成图片出错:', error)
    Message.error('生成图片失败，请重试')
    isGenerating.value = false
    
    // 清除进度条
    if (progressInterval) {
      clearInterval(progressInterval)
      progressInterval = null
    }
  }
}

// 下载图片
const downloadImage = (url: string) => {
  const a = document.createElement('a')
  a.href = url
  a.download = `gilipu-${new Date().getTime()}.png`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 重置生成
const resetGeneration = () => {
  textInput.value = ''
  selectedStyles.value = {
    ghibli: 'none',
    ratio: 'none',
    color: 'none',
    angle: 'none'
  }
  generatedImage.value = ''
  revisedPrompt.value = ''
}

// 测试 CORS 代理
const testCorsProxy = async () => {
  try {
    const response = await fetch('/api/cors-proxy', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const data = await response.json()
      console.log('CORS 代理测试成功:', data)
      Message.success('CORS 代理测试成功')
    } else {
      throw new Error('CORS 代理测试失败')
    }
  } catch (error) {
    console.error('CORS 代理测试出错:', error)
    Message.error('CORS 代理测试失败')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 组件卸载时清除定时器
onMounted(() => {
  return () => {
    if (progressInterval) {
      clearInterval(progressInterval)
    }
  }
})
</script>

<style scoped>
.image-generation-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px 24px 80px 24px; /* 增加底部内边距，确保内容不会被遮挡 */
  min-height: calc(100vh - 48px); /* 设置最小高度，确保内容可以滚动 */
  position: relative;
}

/* 添加全局样式确保页面可滚动 */
:deep(html), :deep(body) {
  height: 100%;
  overflow-y: auto !important;
  margin: 0;
  padding: 0;
}

:deep(#app) {
  min-height: 100vh;
  overflow-y: auto;
}

.generation-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  position: sticky;
  top: 0;
  background: white;
  z-index: 10;
  padding: 12px 0;
}

.back-button {
  margin-right: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.input-section {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.text-input-container {
  display: flex;
  flex-direction: column;
}

.selected-styles {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 12px 0 12px;
}

.style-tag {
  background: rgba(22, 93, 255, 0.1) !important;
  border: none !important;
  color: rgb(22, 93, 255) !important;
}

:deep(.arco-textarea-wrapper) {
  padding: 12px !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.arco-textarea) {
  resize: none !important;
  box-shadow: none !important;
  color: rgb(51, 54, 57) !important;
}

:deep(.arco-textarea):focus {
  box-shadow: none !important;
}

:deep(.arco-textarea)::placeholder {
  color: rgb(134, 144, 156);
}

.input-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: rgb(250, 250, 250);
  border-top: 1px solid rgb(229, 230, 235);
}

.tool-icons {
  display: flex;
  gap: 4px;
}

.tool-btn {
  color: rgb(134, 144, 156) !important;
  width: 32px !important;
  height: 32px !important;
  font-size: 16px !important;
  transition: all 0.2s !important;
}

.tool-btn:hover {
  color: rgb(51, 54, 57) !important;
  background: rgb(242, 243, 245) !important;
}

.tool-btn-active {
  color: rgb(22, 93, 255) !important;
  background: rgba(22, 93, 255, 0.1) !important;
}

.tool-btn-active:hover {
  color: rgb(22, 93, 255) !important;
  background: rgba(22, 93, 255, 0.15) !important;
}

.generate-btn {
  background: rgb(22, 93, 255) !important;
  border-color: rgb(22, 93, 255) !important;
  border-radius: 6px !important;
  padding: 0 16px !important;
  height: 32px !important;
  font-size: 14px !important;
  transition: all 0.2s !important;
}

.generate-btn:hover {
  background: rgb(64, 128, 255) !important;
  border-color: rgb(64, 128, 255) !important;
  transform: translateY(-1px);
}

/* 生成进度页面样式 */
.generation-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 40px 20px 60px 20px; /* 增加底部内边距 */
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 30px; /* 确保底部有足够空间 */
}

.progress-container {
  width: 100%;
  max-width: 500px;
  text-align: center;
  padding-bottom: 20px;
}

.progress-animation {
  margin-bottom: 24px;
}

.loading-icon {
  font-size: 48px;
  color: rgb(22, 93, 255);
}

.progress-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 12px;
  color: rgb(51, 54, 57);
}

.progress-description {
  font-size: 16px;
  color: rgb(78, 89, 105);
  margin-bottom: 32px;
}

.progress-bar-container {
  height: 8px;
  background: rgb(242, 243, 245);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-bar {
  height: 100%;
  background: rgb(22, 93, 255);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-percentage {
  text-align: right;
  font-size: 14px;
  color: rgb(78, 89, 105);
  margin-bottom: 24px;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  margin-bottom: 32px;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 20%;
}

.step-icon {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: rgb(242, 243, 245);
  color: rgb(134, 144, 156);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.step-text {
  font-size: 12px;
  color: rgb(134, 144, 156);
  text-align: center;
  transition: all 0.3s ease;
}

.step.active .step-icon {
  background: rgb(22, 93, 255);
  color: white;
}

.step.active .step-text {
  color: rgb(22, 93, 255);
  font-weight: 500;
}

.generation-tips {
  margin-top: 24px;
  padding: 12px;
  background: rgb(250, 250, 250);
  border-radius: 8px;
}

.generation-tips p {
  margin: 0;
  font-size: 14px;
  color: rgb(134, 144, 156);
}

/* 结果页面样式 */
.result-container {
  margin-top: 24px;
}

.image-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.generated-image {
  width: 100%;
  height: auto;
  object-fit: contain;
}

.image-info {
  padding: 16px;
}

.revised-prompt {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: rgb(78, 89, 105);
  line-height: 1.5;
}

.prompt-label {
  font-weight: 500;
  color: rgb(51, 54, 57);
}

.image-actions {
  display: flex;
  gap: 8px;
}

@media (max-width: 768px) {
  .image-generation-container {
    padding: 16px 16px 60px 16px; /* 增加底部内边距 */
    min-height: calc(100vh - 32px);
  }
  
  .generation-header {
    margin-bottom: 16px;
    padding: 8px 0;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .progress-title {
    font-size: 20px;
  }
  
  .progress-description {
    font-size: 14px;
  }
  
  .step-text {
    font-size: 10px;
  }
  
  .image-actions {
    flex-wrap: wrap;
  }
  
  .generation-progress {
    max-height: none;
    overflow-y: visible;
  }
}
</style>
